// components/DefineSearchSelect/index.js
Component({
  data: {
    searchList: [],
    inputText: '',
    isFocus: false
  },
  searchMsg(option) {
    // option.detail.value
    const that = this
    // 回车值入缓存
    if (option.detail.value != '') {
      try {
        let value = wx.getStorageSync('history')
        if (value) {
          // 最多缓存20条记录
          that.data.searchList = JSON.parse(value).slice(0, 20)
        }
        //去重
        let index = this.data.searchList.indexOf(option.detail.value)
        if (index > -1) {
          this.data.searchList.splice(index, 1)
        }
        that.data.searchList.unshift(option.detail.value)
        wx.setStorageSync('history', JSON.stringify(that.data.searchList))
      } catch (e) {
        console.log(e)
      }
      // 搜索成功后跳转页面，并清空searchList
      this.clearList()
    }
  },
  // 聚焦且无输入值时显示所有历史记录，有输入值时显示包含其的所有历史记录
  showHistory(option) {
    // option.detail.value
    //获取缓存数据
    const that = this
    if (!option.detail.value) {
      try {
        let value = wx.getStorageSync('history')
        if (value) {
          that.setData({
            // 只展示5个
            searchList: JSON.parse(value).slice(0, 5)
          })
        }
      } catch (e) {}
    } else {
      this.findHistory('', option.detail.value)
    }
  },
  //点击历史记录进行填充搜索
  reSearch(e) {
    // e.currentTarget.dataset.text
    this.setData({
      inputText: e.currentTarget.dataset.text,
      // 这个聚焦方法会出现闪动的情况
      isFocus: true
    })
  },
  clearList() {
    this.setData({
      searchList: []
    })
  },
  // 查找搜索历史记录
  findHistory(e, param) {
    // e.detail.value
    const that = this
    let temp = []
    let p = param ? param : e.detail.value
    if (p) {
      try {
        let value = wx.getStorageSync('history')
        if (value) {
          JSON.parse(value).forEach((item, index) => {
            if (item.indexOf(p) > -1) {
              temp.unshift(item)
            }
          })
        }
      } catch (e) {
        console.log(e)
      }
    } else {
      temp = JSON.parse(wx.getStorageSync('history')).slice(0, 5)
    }
    that.setData({
      searchList: temp
    })
  }
})